package com.xpf.ch340_host;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.xpf.ch340_library.CH340Master;
import com.xpf.ch340_library.driver.InitCH340;
import com.xpf.ch340_library.inteface.CallBack;
import com.xpf.ch340_library.inteface.CallBackUtils;
import com.xpf.ch340_library.utils.CH340Util;

/**
 * @author Administrator
 */
public class MainActivity extends AppCompatActivity implements InitCH340.IUsbPermissionListener, CallBack {
    private static final String TAG = "MainActivityaaa";
    /**
     * 判断是否打开
     */
    private boolean isFirst;
    private Button btnSend, btnFormat;
    private EditText etContent;
    private static final String ACTION_USB_PERMISSION = "com.linc.USB_PERMISSION";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSend = findViewById(R.id.btnSend);
        btnFormat = findViewById(R.id.btnFormat);
        etContent = findViewById(R.id.etContent);
        CallBackUtils.setCallBack(this);
        initData();
        initListener();
    }


    private void initListener() {
        btnSend.setOnClickListener(view -> sendData());
        btnFormat.setOnClickListener(view -> {
            String format = btnFormat.getText().toString().toLowerCase();
            if ("ascii".equals(format)) {
                btnFormat.setText("hex");
            } else if ("hex".equals(format)) {
                btnFormat.setText("ascii");
            }
        });
    }

    private void sendData() {
        String string = etContent.getText().toString();
        if (!TextUtils.isEmpty(string)) {
            String format = btnFormat.getText().toString().toLowerCase();
            byte[] bytes = CH340Util.toByteArray2(string);
            CH340Util.writeData(bytes, format);
        } else {
            Toast.makeText(MainActivity.this, "发送的数据不能为空！", Toast.LENGTH_SHORT).show();
        }
    }

    private void initData() {
        InitCH340.setListener(this);
        if (!isFirst) {
            isFirst = true;
            // 初始化 ch340-library
            CH340Master.initialize(MyApplication.getContext());
        }
    }

    @Override
    public void result(boolean isGranted) {
        if (!isGranted) {
            PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
            InitCH340.getmUsbManager().requestPermission(InitCH340.getmUsbDevice(), mPermissionIntent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter usbFilter = new IntentFilter();
        usbFilter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, usbFilter);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            Toast.makeText(MainActivity.this, "EXTRA_PERMISSION_GRANTED~", Toast.LENGTH_SHORT).show();
                            InitCH340.loadDriver(MyApplication.getContext(), InitCH340.getmUsbManager());
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "EXTRA_PERMISSION_GRANTED null!", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUsbReceiver);
    }


    /**
     * @author Weli
     * @time 2017-10-16  10:11
     * @describe //创建Handler对象
     * //新建一个线程对象
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            if (msg.what == 0x102) {
                String receive = bundle.getString("aa");

                if (receive != null) {
                    receive = receive.trim();
                }


                Toast.makeText(MainActivity.this, receive, Toast.LENGTH_SHORT).show();
            }
        }
    };
    @Override
    public void doSomeThing(String string) {
        Log.d(TAG, string);


        Message message = new Message();
        message.what = 0x102;
        Bundle bundle = new Bundle();
        bundle.putString("aa", string);
        message.setData(bundle);
        handler.sendMessage(message);
    }
}
